clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"
cd "${code}/tba_elig"



**** run regressions
cd "${code}/tba_elig"
local flist: dir "${Estimates}" files "reg-ob-cll-*.ster"
foreach f of local flist {
	cap erase "${Estimates}/`f'"
}
local flist: dir "${log}" files "*"
foreach f of local flist {
	cap erase "${log}/`f'"
}

local cmd "sbatch --export=HOME,PATH,SHELL -a 1-90 optimalblue-cll.sh" 
di "`cmd'"

local JobIdFile "${log}/job-id.csv"  
log using `JobIdFile', name("jobid") text replace
shell `cmd'
log close _all

do _sbatch-job "`JobIdFile'" 



*** create tables
preserve
	clear
	cd "${code}/tba_elig"
	run _esttab-latex-options.do

	set obs 1
	gen PaboveC = 1
	gen HiP = 1
	gen HiBal =1 

	run "${code}/_labels"
	label var HiP "$ 1[z_i>0]$"
	label var HiBal "$ \widehat{HiBal}$"
	
	foreach Sample in 1 2 {
		foreach depvar in iv_rate iv_point HiBal point rate {

			eststo clear

			local mgroup ""
			local pattern ""
			local mtitle ""
			foreach w of numlist 150(-50)50 {
				foreach poly of numlist 1/3 {
					estimate use "${Estimates}/reg-ob-cll-`depvar'-poly`poly'-window`w'-Sample`Sample'"
					
					quietly {
						eststo
						
						estadd local llpa "Y"
						estadd local Zip "Y"
						estadd local lockdate "Y"
						estadd local Lender "Y"
						estadd local control "Y"
					}
					if `poly' == 1 local patternadd = 1
					if `poly' > 1 local patternadd = 0
					local pattern "`pattern' `patternadd'"
					local mtitle "`mtitle' `"Poly `poly'"'"
				}
				local mgroup "`mgroup' `"Home Value: 1.25xCLL$\pm$\textdollar`w'K"'"
				
			}
			 				
			if regexm("`depvar'" , "iv_") == 0  {
				local Keep "1.HiP#c.PaboveC1"
				local coeflabels "coeflabels(1.HiP#c.PaboveC1 `"$ z_i\times 1[z_i>0]$"')"
			}
			if regexm("`depvar'" , "iv_") > 0  {
				local Keep "HiBal"
				local coeflabels ""
			}
							
			esttab using "${table}/embs-ob-cll-`depvar'-Sample`Sample'.tex", replace keep(`Keep') `coeflabels' ///
			 ${opts_esttab}  b(%9.4fc) se(%9.4f) star(* 0.10 ** 0.05 *** 0.01) ///
			 stats(llpa Zip Lender lockdate control N r2_a, fmt(%1s %1s %1s %1s %1s %9.0fc %9.3fc) ///
			 labels("LLPA FE" "Zipcode FE" "Lender FE" "Lock Date FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$")) ///
			 mgroup(`mgroup', pattern(`pattern') ${opts_mgroups}) ///
			 mtitle(`mtitle')
		}
	}
restore
